package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String CACHE_KEY_FREEZE_PREFIX = "FREEZE_KEY_";

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    public String savePublish(String textContent, String location, MultipartFile[] files, String longitude, String latitude) {
        //查询登入状态
        User user = UserThreadLocal.get();

        //设置查询redis的key
        String cacheKey = CACHE_KEY_FREEZE_PREFIX + user.getId().toString();
        //根据key去查询redis,判断用户是否被冻结发布
        String key = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.equals(key,"3")){
            return null;
        }

        //不为空
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setSeeType(1);
        publish.setText(textContent);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setLocationName(location);

        //创建集合接收图片名称
        List<String> picUrls = new ArrayList<>();
        for (MultipartFile file : files) {
            PicUploadResult upload = picUploadService.upload(file);
            picUrls.add(upload.getName());
        }
        publish.setMedias(picUrls);


        return quanZiApi.savePublish(publish);


    }


    /**
     * 查看好友动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryPublishList(User user, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        //获取当前登入信息
        Long userId = null;   //默认查询推荐动态

        PageInfo<Publish> pageInfo = null;
        //如果user为null,查询的是推荐动态
        if (null == user) {
            //查询推荐动态
            String key = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String value = redisTemplate.opsForValue().get(key);
            //如果value不为空
            if (StringUtils.isNotEmpty(value)) {
                //命中了数据
                String[] pids = StringUtils.split(value, ",");
                int startIndex = (page - 1) * pageSize;
                if (startIndex < pids.length) {
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length) {
                        endIndex = pids.length - 1;
                    }

                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }
                    //获取到动态
                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }

        if (pageInfo == null) {
            //默认查询逻辑
            if (user != null) {
                //查询好友动态
                userId = user.getId();
            }
            pageInfo = quanZiApi.queryPublishList(userId, page, pageSize);
        }


        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);

        //拿到发布的动态
        List<Publish> records = pageInfo.getRecords();

        //判断获取的好友动态是否为空,如果为空直接返回
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }

        //创建动态集合
        List<Movements> movementsList = new ArrayList<>();
        //不为空,遍历 将发布表中的发布文字图片等数据封装到要返回给前端的Movements对象中
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());   //动态id
            movements.setTextContent(record.getText());   //文本动态
            movements.setUserId(record.getUserId());    //用户id
            movements.setImageContent(record.getMedias().toArray(new String[]{}));   //图片等
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));   //发布时间

            //添加进movementsList集合
            movementsList.add(movements);
        }


        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if (!userIds.contains(movements.getUserId())) {
                userIds.add(movements.getUserId());    //将用户的id封装进新的集合
            }
        }

        //编写查询条件查询数据库拿到用户
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);

        //再将拿到的集合再次进行封装
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                //条件movements中的用户id和userInfo中的用户id相等
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    //调用补全方法
                    fillValueToMovements(movements, userInfo);
                    break;
                }
            }
        }
        //将好友动态封装到pageResult集合中
        pageResult.setItems(movementsList);
        //返回pageResult
        return pageResult;
    }

    /**
     * 推荐动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);

    }

    /**
     * 好友动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        //获取用户id
        User user = UserThreadLocal.get();
        return this.queryPublishList(user, page, pageSize);

    }

    /**
     * 点赞
     *
     * @param publishId
     * @return
     */
    public Long saveLikeComment(String publishId) {
        //获取当前用户信息
        User user = UserThreadLocal.get();
        //调用点赞接口
        Boolean bool = quanZiApi.saveLikeComment(user.getId(), publishId);

        if (!bool) {
            //保存失败
            return null;
        }


        Long likeCount = 0L;
        //保存成功,获取点赞数  应存在redis中  因为数量很大,如果通过mongodb查询,效率偏低
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        //判断redis中是否保存此key
        if (!redisTemplate.hasKey(likeCommentKey)) {
            //获取到评论中点赞的数量
            likeCount = quanZiApi.queryCommentCount(publishId, 1);
            //存入redis中
            redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(likeCount)); //注意应存储String类型
        } else {  //存在
            likeCount = redisTemplate.opsForValue().increment(likeCommentKey);
        }

        //定义标记 记录已点赞
        String likeUserKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.opsForValue().set(likeUserKey, "1");

        return likeCount;
    }

    /**
     * 取消点赞
     *
     * @param publishId
     * @return
     */
    public Long cancelLikeComment(String publishId) {
        //获取当前用户信息
        User user = UserThreadLocal.get();
        //调用dubbo 接口进行取消操作
        Boolean bool = quanZiApi.removeComment(user.getId(), publishId, 1);
        //如果取消失败
        if (!bool) {
            return null;
        }
        //定义redis的key
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        //将redis中的数据递减1
        Long likeCount = redisTemplate.opsForValue().decrement(likeCommentKey);
        //取消成功 ,要将redis中的值删除获取减一

        //删除标记的点赞
        String likeUserKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.delete(likeUserKey);

        return likeCount;
    }

    /**
     * 喜欢
     *
     * @param publishId
     * @return
     */
    public Long saveLoveComment(String publishId) {
        //获取当前用户信息
        User user = UserThreadLocal.get();
        //调用喜欢 接口
        Boolean bool = quanZiApi.saveLoveComment(user.getId(), publishId);
        //喜欢失败
        if (!bool) {
            return null;
        }

        Long loveComment = 0L;
        //喜欢成功 查看redis中是否有数据
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        //如果redis中不存在该数据,则添加到redis中,并喜欢数加1
        if (!redisTemplate.hasKey(loveCommentKey)) {
            //获取评论中喜欢的数量
            loveComment = quanZiApi.queryCommentCount(publishId, 3);
            //存入redis中
            redisTemplate.opsForValue().set(loveCommentKey, String.valueOf(loveComment));
        } else {
            //直接在redis中进行加一操作
            loveComment = redisTemplate.opsForValue().increment(loveCommentKey);
        }

        //定义标记,已喜欢
        String loveUserKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        //存入redis中
        redisTemplate.opsForValue().set(loveUserKey, "1");

        return loveComment;
    }


    /**
     * 取消喜欢
     *
     * @param publishId
     * @return
     */
    public Long cancelLoveComment(String publishId) {
        //获取当前用户信息
        User user = UserThreadLocal.get();
        //调用dubbo 接口进行取消操作
        Boolean bool = quanZiApi.removeComment(user.getId(), publishId, 3);
        //如果取消失败
        if (!bool) {
            return null;
        }
        //定义redis的key
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        //将redis中的数据递减1
        Long lioveCount = redisTemplate.opsForValue().decrement(loveCommentKey);
        //取消成功 ,要将redis中的值删除获取减一

        //删除标记的点赞
        String loveUserKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        redisTemplate.delete(loveUserKey);

        return lioveCount;
    }

    /**
     * 查询单条动态
     *
     * @param publishId
     * @return
     */
    public Movements querypublishById(String publishId) {
        //获取发布动态的信息
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        //判断是否为空
        if (null == publish) {
            return null;
        }

        //创建Movements对象
        Movements movements = new Movements();
        movements.setId(publish.getId().toHexString()); //动态id
        movements.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));  //发布时间
        movements.setTextContent(publish.getText());
        movements.setImageContent(publish.getMedias().toArray(new String[]{}));
        movements.setUserId(publish.getUserId());

        //查询数据库中的用户信息表
        UserInfo userInfo = userInfoService.queryById(publish.getUserId());
        //非空处理
        if (null == userInfo) {
            return null;
        }
        //调用补全方法
        fillValueToMovements(movements, userInfo);

        return movements;

    }


    /**
     * 补全信息
     *
     * @param movements
     * @param userInfo
     */
    private void fillValueToMovements(Movements movements, UserInfo userInfo) {
        User user = UserThreadLocal.get();
        movements.setAge(userInfo.getAge());  //年龄
        movements.setNickname(userInfo.getNickName());  //名称
        movements.setAvatar(userInfo.getLogo());   //头像
        movements.setGender(userInfo.getSex().toString());
        movements.setTags(StringUtils.split(userInfo.getTags(), ","));
        movements.setCommentCount(10);   // TODO: 评论数
        movements.setDistance("1.2公里"); // TODO: 距离

        String likeUserKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
        movements.setHasLiked(redisTemplate.hasKey(likeUserKey) ? 1 : 0);   //TODO 是否点赞(1是 , 0否)

        String loveUserKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
        movements.setHasLoved(redisTemplate.hasKey(loveUserKey) ? 1 : 0);  //TODO 是否喜欢 (1是,0否)

        //从redis中获取点赞数
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
        String likeCommentValue = (String) this.redisTemplate.opsForValue().get(likeCommentKey);

        //如果从redis中获取的点赞数为空,则默认赋值为0
        if (StringUtils.isNotEmpty(likeCommentValue)) {
            movements.setLikeCount(Integer.valueOf(likeCommentValue));  //TODO 点赞数
        } else {
            movements.setLikeCount(0);
        }


        //从redis中获取喜欢数
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
        String loveCommentValue = this.redisTemplate.opsForValue().get(loveCommentKey);
        //如果从redis中获取的喜欢数为空,则默认赋值为0
        if (StringUtils.isNotEmpty(loveCommentValue)) {
            movements.setLoveCount(Integer.valueOf(loveCommentValue));  //TODO 喜欢数
        } else {
            movements.setLoveCount(0); //TODO 喜欢数
        }

    }


    /**
     * 谁看过我
     *
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        //获取当前用户信息
        User user = UserThreadLocal.get();

        List<Visitors> visitors = null;
        //如果redis中,存在上一次查询的时间点的话就按照时间查询,否则就按照数量查询
        String redisKey = "visitors_" + user.getId();
        String data = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(data)) {
            //按照数量查询
            visitors = visitorsApi.topVisitor(user.getId(), 6);
        } else {
            //按照时间查询
            visitors = visitorsApi.topVisitor(user.getId(), Long.valueOf(data));
        }
        //如果返回的集合为空,直接返回一个空集合,防止前端报错
        if (CollectionUtils.isEmpty(visitors)) {
            return Collections.emptyList();
        }

        //获取到来访用户的id
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        //创建集合封装返回的数据
        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                //一一对应
                if (visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());  //年龄
                    visitorsVo.setAvatar(userInfo.getLogo());  //头像
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ","));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }


    /**
     * 查询自己的所有动态
     *
     * @param userId   佳人id
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {

        //创建返回的PageResule对象,并设置基本参数
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        //调用接口获取相册表中的动态
        PageInfo<Publish> pageInfo = quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();

        //非空处理
        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }
        //创建返回的动态封装VO
        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            //添加到集合中
            movementsList.add(movements);

        }

        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if (!userIds.contains(movements.getUserId())) {
                userIds.add(movements.getUserId());
            }
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);

        //查询到数据的信息再一一进行封装
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillValueToMovements(movements, userInfo);
                    break;
                }
            }
        }

        pageResult.setItems(movementsList);
        return pageResult;
    }
}
